using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using Idp_Login.Service;

namespace Idp_Login
{
    /*
Ids4校验流程
1、校验客户端Client_id和Client_Secret。
2、校验客户端是否有当前的授权方式。
3、校验是否有请求scope权限。
4、如果非客户端验证，校验账号密码或自定义规则是否正确。
5、非客户端验证，校验授权信息是否有效。
     */

    /// <summary>
    /// 自定义校验器
    /// 使用方式 :
    /// 1. 需要.AddExtensionGrantValidator<CustomGrantValidator>();
    /// 2.数据库表(dbo.ClientGrantTypes)需要添加 GrantType CustomGrantType  
    /// 
    /// </summary>
    public class CustomGrantValidator : IExtensionGrantValidator
    {
        public string GrantType => "CustomGrantType";

        private readonly IAdminService _adminService;

        public CustomGrantValidator(IAdminService adminService)
        {
            this._adminService = adminService;
        }
        public Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            var CE_name = context.Request.Raw.Get("CE_name");
            var CE_password = context.Request.Raw.Get("CE_password");
            Console.WriteLine($"This is CustomElevenGrantValidator CE_name={CE_name}--CE_password={CE_password}");

            if (string.IsNullOrEmpty(CE_name) || string.IsNullOrEmpty(CE_password))
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
            }
            var result = this._adminService.GetByUserNameAndPwd(CE_name, CE_password);
            if (result == null)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
            }
            else
            {
                List<Claim> Claims = new List<Claim>()
                {

                };

                Console.WriteLine($"This is CustomElevenGrantValidator CE_name={CE_name}--CE_password={CE_password}");
                context.Result = new GrantValidationResult(
                    subject: result.Id.ToString(),
                    authenticationMethod: GrantType,
                    claims: Claims);
            }
            return Task.CompletedTask;
        }
    }
}
